package app

import (
	"strings"
	"time"

	"github.com/spf13/viper"

	klog "kiwi/log"
)

func CreateLoggerOption(cfg *viper.Viper) *klog.LoggerOption {
	if cfg == nil {
		return nil
	}

	o := &klog.LoggerOption{}

	o.Name = cfg.GetString("name")

	sLevel := strings.ToLower(cfg.GetString("level"))
	switch sLevel {
	case "debug":
		o.Level = klog.LevelDebug
	case "info":
		o.Level = klog.LevelInfo
	case "warn":
		o.Level = klog.LevelWarn
	case "error":
		o.Level = klog.LevelError
	default:
		o.Level = klog.LevelDebug
	}

	o.TimestampFormat = cfg.GetString("timestampformat")

	o.Caller = cfg.GetBool("caller")

	o.CallerSkip = cfg.GetInt("callerskip")

	o.Console = cfg.GetBool("console")

	o.ConsoleColorful = cfg.GetBool("consolecolorful")

	return o
}

func CreateLogFileOption(name string, cfg *viper.Viper) *klog.FileOption {
	if cfg == nil {
		return nil
	}

	o := &klog.FileOption{}

	o.Name = cfg.GetString("name")

	if o.Name == "" {
		o.Name = name
	}

	o.Dir = cfg.GetString("dir")

	o.MaxSize = cfg.GetInt64("maxsize")

	o.MaxAge = cfg.GetDuration("maxage") * 24 * time.Hour

	// todo SeperatedLevels待定

	o.TickInterval = cfg.GetDuration("tickinteval") * time.Second

	return o
}

func CreateLogger(name string, loggerConfig *viper.Viper, fileConfig *viper.Viper) (klog.ILogger, error) {
	var logger klog.ILogger
	var err error

	if loggerConfig == nil {
		logger, err = klog.CreateLogger(nil)
		if err != nil {
			return nil, err
		}
	}

	loggerOption := &klog.LoggerOption{}
	loggerOption.Load(loggerConfig)

	if loggerOption.Name == "" {
		loggerOption.Name = name
	}

	var fileWriter klog.IWriter

	if loggerConfig.GetBool("file") {
		fileOption := &klog.FileOption{}

		fileOption.Load(name, fileConfig)

		if fileOption.Name == "" {
			fileOption.Name = name
		}

		fileWriter, err = klog.CreateFileWriter(fileOption)
		if err != nil {
			return nil, err
		}
	}

	logger, err = klog.CreateLogger(loggerOption, fileWriter)

	return logger, err
}
